package com.sky.aspect;


import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import org.apache.poi.ss.formula.functions.T;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Objects;

@Component
@Aspect
public class AutoFillAspect {


    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void joinpointMethod() {
    }

    @Before("joinpointMethod()")
    public void pc(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        //1 获取注解的值，来判断操作是insert还是update
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();//获得签名
        AutoFill autoFill = methodSignature.getMethod().getAnnotation(AutoFill.class);//获得注解对象
        OperationType type = autoFill.type();

        //2  获取方法的参数，用于填充字段
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            return;
        }
        Object arg = args[0];

        //3 获取要赋予的值
        LocalDateTime time = LocalDateTime.now();
        Long id = BaseContext.getCurrentId();

        if (Objects.isNull(arg) || Objects.isNull(type)) {
            return;
        }
        //4 赋值 利用反射
        if (type == OperationType.INSERT) {
            Method setCreateTime = arg.getClass().getDeclaredMethod
                    (AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
            Method setUpdateTime = arg.getClass().getMethod
                    (AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method setCreateUser = arg.getClass().getDeclaredMethod
                    (AutoFillConstant.SET_CREATE_USER, Long.class);
            Method setUpdateUser = arg.getClass().getMethod
                    (AutoFillConstant.SET_UPDATE_USER, Long.class);

            setCreateTime.invoke(arg, time);
            setUpdateTime.invoke(arg, time);
            setCreateUser.invoke(arg, id);
            setUpdateUser.invoke(arg, id);
        } else if (type == OperationType.UPDATE) {
            Method setUpdateUser = arg.getClass().getMethod
                    (AutoFillConstant.SET_UPDATE_USER, Long.class);
            Method setUpdateTime = arg.getClass().getMethod
                    (AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            setUpdateUser.invoke(arg, id);
            setUpdateTime.invoke(arg, time);

        }


    }
}
